//
//  WJLkdbUtils.m
//  JerryIos
//
//  Created by 王军 on 2018/2/16.
//  Copyright © 2018年 王军. All rights reserved.
//

#import "WJLkdbUtils.h"
#import <LKDBHelper.h>
#import "WJLkdbData.h"

@implementation WJLkdbUtils

static LKDBHelper *db;

+(void)initialize {
    //第一种方式
    db = [[LKDBHelper alloc]init];
    //        //第二种方式
    //        NSString* dbpath = [NSHomeDirectory() stringByAppendingPathComponent:@"asd/asd.db"];
    //        db = [[LKDBHelper alloc]initWithDBPath:dbpath];
}

+(BOOL) addData:(WJLkdbData *)data {
    //第一种方式
//    [data saveToDB];
    //第二种方式
    return [WJLkdbData insertToDB:data];
}

+(BOOL) updateData:(WJLkdbData *)data {
    return [data updateToDB];
}

+(BOOL) updateDataById:(WJLkdbData *)data id:(int)id {
    NSString *whereSql = [NSString stringWithFormat:@"id = %i",id];
    return [WJLkdbData updateToDB:data where:whereSql];
}

+(BOOL) deleteData:(WJLkdbData *)data {
    return [WJLkdbData deleteToDB];
}

+(BOOL) deleteDataById:(int)id {
    NSString *whereSql = [NSString stringWithFormat:@"id = %i",id];
    return [WJLkdbData deleteWithWhere:whereSql];
}




+(void) addDataArray:(NSArray *)dataArray {
    [WJLkdbData insertArrayByAsyncToDB:dataArray];
}

+(void) updateDataArray:(NSArray *)dataArray {
    [db executeForTransaction:^BOOL(LKDBHelper * _Nonnull helper) {
        for (WJLkdbData *data in dataArray) {
            if (![self updateData:data]) {
                return NO;
                break;
            }
        }
        return YES;
    }];
}

+(void) deleteDataArray:(NSArray *) idArray {
    [db executeForTransaction:^BOOL(LKDBHelper * _Nonnull helper) {
        for (int i=0; i<idArray.count; i++) {
            NSString *idStr = idArray[i];
            if (![self deleteDataById:[idStr intValue]]) {
                return NO;
                break;
            }
        }
        return YES;
    }];
}




+(NSArray *) dataAll {
    NSString *sql = [NSString stringWithFormat:@"select * from %@",WJLkdbData.getTableName];
    NSArray *dataArray = [WJLkdbData searchWithSQL:sql];
    return dataArray;
}

+(WJLkdbData *) dataById:(int)id {
    NSString *whereSql = [NSString stringWithFormat:@"id = %i",id];
    NSArray *dataArray = [WJLkdbData searchWithWhere:whereSql];
    if([dataArray count] > 0) {
        return dataArray[0];
    }
    return nil;
}

+(int) getMaxId {
    NSArray *dataArray = [self dataAll];
    int maxId = 0;
    for (WJLkdbData *data in dataArray) {
        if (maxId < data.id) {
            maxId = data.id;
        }
    }
    return maxId;
}

+(NSInteger) getCountByName:(NSString *)name {
    NSString *whereSql = [NSString stringWithFormat:@"name = %@",name];
    NSInteger count = [WJLkdbData rowCountWithWhere:whereSql];
    return count;
}

@end
